<template>
	<a-layout style="height: 100%;">
		<a-layout-sider class="leftsider" :width="siderWidth" style="margin: 10px 10px 10px 0;">
			<deptTree @selected="selectTree" ref="deptTree"></deptTree>
			<img src="../../../assets/img/arrow.png" class="arrow" :class="{ close: siderWidth == 0 }" @click="siderWidth = siderWidth == 220 ? 0 : 220" />
		</a-layout-sider>
		<a-layout-content>
			<pro-table
				ref="protable"
				:loadDataUrl="api.getList"
				:paramstype="1"
				rowKey="userId"
				:columns="columns"
				@selectedRowChange="onSelectChange"
				:extendParam="extendParam"
				@setTableData="setTableData"
				@handlerReset="handlerReset"
			>
				<template slot="hd-button">
					<a-space :size="8">
						<a-button class="ant-btn-blue" v-has="'sys:user:add'" @click="addRecord()">新增</a-button>
						<a-button class="ant-btn-red" v-has="'sys:user:del'" :disabled="selectedRowKeys.length <= 0" @click="showDeleteConfirm(0)">删除</a-button>
						<a-button class="ant-btn-yellow" v-has="'sys:user:dept'" :disabled="selectedRowKeys.length <= 0" @click="showChangeDept()">批量换部门</a-button>
					</a-space>
				</template>
				<span slot="operation" slot-scope="{ text, record }" class="operation" v-if="record.accountType !== 'ADMIN'">
					<a href="javascript:;" v-has="'sys:user:edit'" title="编辑" class="edit" @click="editRecord(record)">编辑</a>
					<a href="javascript:;" v-has="'sys:user:del'" title="删除" class="del" @click="showDeleteConfirm(1, record)">删除</a>
					<a href="javascript:;" v-has="'sys:user:restPwd'" title="重置密码" class="add" @click="showResetPwdConfirm(1, record)">重置密码</a>
				</span>
				<template slot="avatar" slot-scope="{ text, record, index }">
					<img :src="fileUrl + record.avatarThumbnail" :large="fileUrl + text" v-if="text" class="avatar" :preview="index" :preview-text="record.name" />
				</template>
				<div slot="roleNames" slot-scope="{ text, record }">
					<a-tooltip placement="topLeft" v-for="(item, index) in text">
						<template slot="title">
							<span>{{ item }}</span>
						</template>
						<div>{{ item }}</div>
					</a-tooltip>
				</div>
				<div slot="deptName" slot-scope="{ text, record }">
					<a-tooltip placement="topLeft" v-for="(item, index) in text">
						<template slot="title">
							<span>{{ item.deptName }}</span>
						</template>
						<div>{{ item.deptName }}</div>
					</a-tooltip>
				</div>
				<span slot="accountType" slot-scope="{ text, record }">{{ text == 'ADMIN' ? '超级管理员' : text == 'OTHER' ? '普通账户' : '运维账户' }}</span>
				<a-tag :color="text == 1 ? '#00a095' : '#d43030'" slot="status" slot-scope="{ text }">{{ text == 1 ? '启用' : '停用' }}</a-tag>
				<!-- 添加，编辑 -->
				<add-or-edit-user-modal :api="api" modalTitle="账号" ref="addOrEditModal" @ok="handlerRefresh"></add-or-edit-user-modal>
				<!-- 角色 -->
				<set-role-modal ref="setRoleModal" @ok="handlerRefresh"></set-role-modal>
				<!-- 重置密码 -->
				<rest-password-modal ref="restPasswordModal"></rest-password-modal>
				<!-- 批量换部门 -->
				<change-farm-modal ref="changeFarmModal" @selectDept="changeDept"></change-farm-modal>
			</pro-table>
		</a-layout-content>
	</a-layout>
</template>

<script>
import { rowSelection, recordOperation } from '@/mixins';
import { sysManageapi } from '@/api/index.js';
import addOrEditUserModal from '../module/addOrEditUserModal';
import restPasswordModal from '../module/restPasswordModal';
import setRoleModal from '../module/setRoleModal';
import changeFarmModal from '@/components/changeFarmModal.vue';
import { SEXTYPE } from '@/utils/enumeration';
import { mapState, mapMutations, mapActions } from 'vuex';
import deptTree from '@/components/deptTree.vue';
const columns = [
	{
		title: '所属机构',
		dataIndex: 'orgName',
		key: 'orgName',
		searchInfo: {
			value: 'orgId',
			type: 'select',
			defaultValue: undefined,
			optionlist: []
		}
	},
	{
		title: '头像',
		dataIndex: 'avatar',
		key: 'avatar',
		align: 'center',
		scopedSlots: {
			customRender: 'avatar'
		}
	},
	{
		title: '账户',
		dataIndex: 'username',
		key: 'username',
		searchInfo: {
			type: 'string',
			defaultValue: ''
		}
	},
	{
		title: '姓名',
		dataIndex: 'name',
		key: 'name',
		searchInfo: {
			type: 'string',
			defaultValue: ''
		}
	},
	{
		title: '部门名称',
		dataIndex: 'depts',
		key: 'depts',
		scopedSlots: {
			customRender: 'deptName'
		}
	},
	{
		title: '账户类型',
		dataIndex: 'accountType',
		key: 'accountType',
		scopedSlots: {
			customRender: 'accountType'
		}
	},
	{
		title: '角色',
		dataIndex: 'roleNames',
		key: 'roleNames',
		scopedSlots: {
			customRender: 'roleNames'
		}
	},
	{
		title: '邮箱',
		key: 'email',
		dataIndex: 'email',
		ellipsis: true
	},
	{
		title: '手机号码',
		key: 'phonenumber',
		dataIndex: 'phonenumber',
		ellipsis: true,
		searchInfo: {
			type: 'string',
			defaultValue: ''
		}
	},
	{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
		align: 'center',
		width: 100,
		scopedSlots: {
			customRender: 'status'
		},
		searchInfo: {
			type: 'select',
			defaultValue: undefined,
			optionlist: [
				{
					value: 1,
					text: '启用'
				},
				{
					value: 0,
					text: '停用'
				}
			]
		}
	},
	{
		title: '操作',
		key: 'operation',
		dataIndex: 'operation',
		scopedSlots: { customRender: 'operation' },
		align: 'center',
		width: 200,
		fixed: 'right'
	}
];
export default {
	name: 'userlist',
	mixins: [rowSelection, recordOperation],
	components: {
		addOrEditUserModal,
		setRoleModal,
		restPasswordModal,
		changeFarmModal,
		deptTree
	},
	data() {
		return {
			columns: [],
			api: sysManageapi.userUrl,
			treeData: [],
			alltreeData: [],
			treeKeys: [],
			autoExpandParent: false,
			expandedKeys: [],
			loadedKeys: [],
			searchValue: '',
			extendParam: {},
			replaceFields: { children: 'children', title: 'deptName', key: 'deptId', value: 'deptId' },
			siderWidth: 220,
			fileUrl: process.env.VUE_APP_FILE_API,
			tablelist: []
		};
	},
	computed: {
		...mapState(['user', 'deptTree'])
	},
	created() {
		if (this.deptTree.length == 0) {
			this.getDeptTree();
		}
		this.columns = columns.filter(item => {
			if (!(!this.isAdmin && item.key == 'accountType')) {
				return item;
			}
		});
		// this.getAllOrgList();
	},
	methods: {
		...mapActions(['getDeptTree']),
		/* 添加 */
		addUser() {
			let param = {};
			if (this.extendParam.deptId) {
				let { deptId, deptName } = this.selectedDept;
				param = {
					deptId,
					deptName
				};
			}
			this.$refs.addOrEditUserModal.add(param);
		},
		/* 编辑 */
		edit(record) {
			this.$refs.addOrEditUserModal.edit(record);
		},
		/* 确认重置密码 */
		showResetPwdConfirm(type, record) {
			this.$refs.restPasswordModal.resetPwd(record);
		},

		/* 确认删除用户 */
		showDeleteConfirm(type, record) {
			let _this = this;
			let title, ids;
			if (type == 0) {
				title = '你确定删除选中的' + this.selectedRowKeys.length + '条数据的吗？';
				ids = this.selectedRowKeys.map(item => item);
			} else {
				title = (
					<div>
						你确定要删除
						<span style="color:red;">
							{record.username}
							{record.name ? '(' + record.name + ')' : ''}
						</span>
						吗?
					</div>
				);
				ids = [record.userId];
			}
			this.$confirm({
				title: title,
				content: '删除后用户信息将不能恢复',
				okText: '确定',
				cancelText: '取消',
				class: 'confirmbox',
				okType: 'danger',
				onOk() {
					_this.removeUser(ids);
				},
				onCancel() {}
			});
		},
		/* 删除用户 */
		removeUser(usernames) {
			this.$postAction(sysManageapi.userUrl.delete, usernames).then(da => {
				if (da.code == 1) {
					this.$message.success('删除用户成功！');
					this.handlerRefresh();
				}
			});
		},
		/* 刷新列表当前页 */
		handlerRefresh() {
			this.$refs.protable.handlerRefresh();
		},
		/* 选中部门，刷新列表 */
		selectTree(selectedDept) {
			this.selectedDept = !!selectedDept ? { ...selectedDept } : null;
			this.extendParam = {
				deptId: !!selectedDept ? this.selectedDept.deptId : ''
			};
			this.$nextTick(() => {
				// this.handlerRefresh();
        this.$refs.protable.$refs.reffilter.search();
			});
		},
		/* 批量修改部门 */
		showChangeDept() {
			/* 先判断一下是否为同一机构下的用户 */
			let orgIdList = [];
			this.tablelist.forEach(item => {
				if (this.selectedRowKeys.includes(item.userId) && !orgIdList.includes(item.orgId)) {
					orgIdList.push(item.orgId);
				}
			});
			if (orgIdList.length > 1) {
				this.$message.error('请选择同一个机构下的用户切换部门');
				return;
			}
			this.$refs.changeFarmModal.show(orgIdList[0], 'default','ALL');
		},
		/* 确认修改部门 */
		changeDept(deptList) {
			let deptArr=Array.isArray(deptList)?deptList:[deptList];
			this.$postAction(sysManageapi.userUrl.usersChangeDept, {
				deptIds: deptArr.map(item => item.deptId),
				userIds: this.selectedRowKeys
			}).then(res => {
				if (res && res.code == 1) {
					this.$message.success('保存成功');
					this.handlerRefresh();
				}
			});
		},
		/* 设置角色 */
		setRole(record) {
			this.$refs.setRoleModal.show(record);
		},
		getAllOrgList() {
			this.$postAction(sysManageapi.orgUrl.getAllOrgList).then(res => {
				if (res && res.code == 1) {
					let list = res.data,
						optionlist = [];
					if (list && list.length > 0) {
						list.forEach((item, index) => {
							optionlist.push({
								value: item.orgId,
								text: item.orgName
							});
						});
					}
					this.columns[0].searchInfo.optionlist = optionlist;
				}
			});
		},
		setTableData(list) {
			this.tablelist = [...list];
		},
		handlerReset() {
			!!this.$refs.deptTree && (this.$refs.deptTree.treeKeys = []);
			this.selectTree('');
		}
	}
};
</script>

<style scoped="scoped" lang="less">
.avatar {
	width: 60px;
	height: 60px;
	border-radius: 8px;
	display: block;
	margin: 0 auto;
}
.leftsider {
	background: #fff;
	position: relative;
	.arrow {
		position: absolute;
		top: 50%;
		left: 100%;
		z-index: 999;
		transform: translate(0, -50%);
		cursor: pointer;
		&.close {
			transform: translate(0, -50%) scaleX(-1);
		}
	}
}
</style>
